const express = require('express');
const cors = require('cors');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const PORT = 3000;


// 引入数据库连接池
const pool = require('./db');

// 使用JSON中间件
app.use(express.json());
app.use(cors({
    origin: 'http://localhost:7000',  // 确保允许来自前端的请求
    methods: 'GET,POST,PUT,DELETE',
    allowedHeaders: 'Content-Type,Authorization',
}));

// 处理 OPTIONS 请求
app.options('*', cors());

// 测试数据库连接
async function testDatabaseConnection() {
    try {
        const connection = await pool.getConnection();
        console.log('Database connection successful!');
        connection.release();
    } catch (err) {
        console.error('Database connection failed:', err);
    }
}

// 调用测试函数
testDatabaseConnection();

// 使用路由
const authRoutes = require('./routes/auth');
const postRoutes = require('./routes/posts');
const aiRoutes = require('./routes/ai'); // 引入 ai 路由
const booksApi = require('./routes/books'); // 引入书籍 API
const settingAPI = require('./routes/mysetting');


app.use('/api/auth', authRoutes);
app.use('/api/community', postRoutes);
app.use('/api/ai', aiRoutes); // 使用 ai 路由
// 使用书籍 API
app.use('/api', booksApi);
app.use('/api/setting', settingAPI);

// 创建 HTTP 服务器
const server = http.createServer(app);

// 设置 WebSocket
const io = socketIo(server, {
    cors: {
        origin: 'http://localhost:7000', // 允许来自前端的 WebSocket 请求
        methods: ['GET', 'POST'],
        allowedHeaders: ['Content-Type', 'Authorization'],
    }
});

// WebSocket 连接处理
io.on('connection', (socket) => {
    console.log('A user connected');

    // 处理 WebSocket 消息
    socket.on('message', (data) => {
        console.log('Message from client: ', data);
        socket.emit('response', `You sent: ${data}`);
    });

    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});

// 启动 HTTP 和 WebSocket 服务器
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});